package com.study.common.util;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Base64Util {
	
	public static final Logger logger = LoggerFactory.getLogger(AESPlus.class);
	
	public static final String CHARSET = "utf-8";
	
    // 加密
    public static String encodeString(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes(CHARSET);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }
    
    public static String encodeByte(byte[] b) {
    	String s = null;
    	if (b != null) {
    		s = new BASE64Encoder().encode(b);
    	}
    	return s;
    }

    // 解密
    public static String decodeToString(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, CHARSET);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        return result;
    }
    
    public static byte[] decodeToByte(String s) {
    	byte[] b = null;
    	if (s != null) {
    		BASE64Decoder decoder = new BASE64Decoder();
    		try {
    			b = decoder.decodeBuffer(s);
    		} catch (Exception e) {
    			logger.error(e.getMessage());
    		}
    	}
    	return b;
    }

    public static byte[] decodeImg(String imgStr) {
        byte[] b = null;
        if (!StringUtils.isNotBlank(imgStr)) {
            return b;
        }
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; i++) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return b;
    }


}